﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using DevExpress.XtraEditors;
using Speed.Data;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmTaskDetail : XtraFormBase
    {
        #region "Private Variable"
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int ConDetId;
        #endregion

        #region "Form Construction"
        public FrmTaskDetail()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
           
        }
        #endregion

        #region "Private Method"
        private void BlankForm()
        {
            grdDetail.DataSource = ClsTask.ListDetail(ConDetId);
            EmpSearchLookUpEdit.DataSource = ClsEmployees.SelectAll();
            EmpSearchLookUpEdit.ValueMember = "ID";
            EmpSearchLookUpEdit.DisplayMember = "FullName";
        }

        
        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);
            DataTable dtSource = (DataTable)grdDetail.DataSource;

            var listAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            var listUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            var listDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));

            try
            {
                using (var db = Sys.NewDb())
                {
                    db.BeginTransaction();
                    foreach (var addItem in listAdd)
                    {
                        db.Insert<Task>(addItem);
                    }
                    foreach (var updateItem in listUpdate)
                    {
                        db.Update<Task>(updateItem);
                    }
                    foreach (var delItem in listDelete)
                    {
                        db.Delete<Task>(string.Format("TaskId={0}", delItem.TaskId));
                    }
                    db.Commit();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private List<Task> GetListAdd(DataTable dataTable)
        {
            List<Task> list = new List<Task>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    Task item = new Task();
                    item.TaskId = 0;
                    item.ConDetId = ConDetId;
                    item.TaskName = String.Format("{0}", row["TaskName"]);
                    item.TaskDescription = String.Format("{0}", row["TaskDescription"]);
                    item.TaskNumDay = row["TaskNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["TaskNumDay"]);
                    if (!row.IsNull("TaskBeginDate"))
                    {
                        item.TaskBeginDate = Convert.ToDateTime(row["TaskBeginDate"]);
                    }
                    if (!row.IsNull("TaskEndDate"))
                    {
                        item.TaskEndDate = Convert.ToDateTime(row["TaskEndDate"]);
                    }
                    if (!row.IsNull("EmpId"))
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<Task> GetListUpdate(DataTable dataTable)
        {
            List<Task> list = new List<Task>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    Task item = new Task();
                    item.TaskId = Convert.ToInt32(row["TaskId"]);
                    item.ConDetId = ConDetId;
                    item.TaskName = String.Format("{0}", row["TaskName"]);
                    item.TaskDescription = String.Format("{0}", row["TaskDescription"]);
                    item.TaskNumDay = row["TaskNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["TaskNumDay"]);
                    if (!row.IsNull("TaskBeginDate"))
                    {
                        item.TaskBeginDate = Convert.ToDateTime(row["TaskBeginDate"]);
                    }
                    if (!row.IsNull("TaskEndDate"))
                    {
                        item.TaskEndDate = Convert.ToDateTime(row["TaskEndDate"]);
                    }
                    if (!row.IsNull("EmpId"))
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<Task> GetListDelete(DataTable dataTable)
        {
            List<Task> list = new List<Task>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    Task item = new Task();
                    item.TaskId = Convert.ToInt32(row["TaskId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        #endregion

        #region "Background Worker"

        
        #endregion

        #region "Form Event"
        private void FrmTaskDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            btnSave.Enabled = ConDetId>0;
            btnDesign.Enabled = !OnlyView;
            grvDetail.OptionsBehavior.Editable = ConDetId > 0;
            //if (!String.IsNullOrEmpty(FormXtraGridLayoutTemplate))
            //{
            //    var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
            //    grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            //}
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        

        
    }
}
